package com.zy.mc_module;

import android.app.ActivityManager;
import android.content.Context;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.view.KeyEvent;

import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.zy.mc_module.base.App;
import com.zy.mc_module.base.BaseActivity;
import com.zy.mc_module.common.RxBusCode;
import com.zy.mc_module.ui.shortvideo.ShortVideoFragment;
import com.zy.mc_module.utils.StatusBarUtil;
import com.zy.mc_module.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/***
 * Created on 18/10/24
 * MainActivity
 */
public class MainActivity extends BaseActivity {

    //    @BindView(R.id.main_viewpager)
    //    NSViewPager mainViewpager;
    @BindView(R.id.main_navigation)
    BottomNavigationView mainNavigation;
    private ArrayList<Fragment> fragments;
    private int mPosition = 0;

    private long firstTime = 0;
    private Fragment currentFragment = new Fragment();
    //    private final int[] selectIcons = new int[]{R.drawable.home_select,
//            R.drawable.find_select,
//            R.drawable.wuy_select,
//    R.drawable.wuy_selected,
//    R.drawable.partner_selected,
//            R.drawable.car_select,
//            R.drawable.mine_select};
    private final int[] selectedIcons = new int[]{R.mipmap.index002,
            R.mipmap.index004,
            R.mipmap.index006,
            R.mipmap.index008};
    private final int[] unSelectedIcons = new int[]{R.mipmap.index001,
            R.mipmap.index003,
            R.mipmap.index005,
            R.mipmap.index007};

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean isNeedRxBus() {
        return true;
    }

    @Override
    protected void initView() {
        StatusBarUtil.setImmersiveStatusBar(this);
        mainNavigation.setItemIconTintList(null);
        //当窗体加载完毕时，执行
        getWindow().getDecorView().postDelayed(() -> {
            //checkVersion();
            initFragment();
            getData();
        }, 25);
    }

    /***
     * 初始化Fragment
     */
    private void initFragment() {
        fragments = new ArrayList<>();
        fragments.add(new ShortVideoFragment());
        fragments.add(new ServiceFragment());
        fragments.add(new FindFragment());
        fragments.add(new MineFragment());
        //--------默认选中第一个fragment
        switchFragment(fragments.get(0));
        mainNavigation.getMenu().getItem(0).setChecked(true);
        mainNavigation.getMenu().getItem(0).setIcon(selectedIcons[0]);
    }

    @Override
    protected void initListener() {
        mainNavigation.setOnNavigationItemSelectedListener(menuItem -> {
            switch (menuItem.getItemId()) {
                case R.id.item_home:
                    setCurrentTab(0, true);
                    return true;
                case R.id.item_find:
                    setCurrentTab(1, true);
                    return true;
                case R.id.item_car:
                    setCurrentTab(2, true);
                    return true;
                case R.id.item_mine:
                    setCurrentTab(3, true);
                    return true;
            }
            return false;
        });
    }

    /**
     * zonme
     * 选中fragment
     *
     * @param targetFragment
     */
    private void switchFragment(Fragment targetFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
            //第一次使用switchFragment()时currentFragment为null，所以要判断一下
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
            transaction.add(R.id.frameContent, targetFragment, targetFragment.getClass().getName());
        } else {
            transaction.hide(currentFragment).show(targetFragment);
        }
        currentFragment = targetFragment;
        transaction.commitAllowingStateLoss();
    }

    /***
     * 切换fragment和底部Tab
     */
    public void setCurrentTab(int position, boolean mainPage) {
        if (position == mPosition && mainPage) return;
        try {
            if (position >= 0 && fragments.size() > position) {
                switchFragment(fragments.get(position));
                mainNavigation.getMenu().getItem(position).setChecked(true);
//                GifDrawable gifDrawable = new GifDrawable(getResources(), selectIcons[position]);
//                gifDrawable.addAnimationListener(new AnimationListener() {
//                    @Override
//                    public void onAnimationCompleted(int loopNumber) {
//                        mainNavigation.getMenu().getItem(position).setIcon(getResources().getDrawable(selectedIcons[position]));
//                    }
//                });
                mainNavigation.getMenu().getItem(position).setIcon(selectedIcons[position]);
                mainNavigation.getMenu().getItem(mPosition).setIcon(getResources().getDrawable(unSelectedIcons[mPosition]));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mPosition = position;
    }

    /***
     * 获取首页数据
     */
    private void getData() {

    }

    //检测服务是否在运行中
    public static boolean isServiceRunning(Class<?> serviceClass, Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(Integer.MAX_VALUE);
        if (serviceList == null || serviceList.size() == 0)
            return false;
        for (ActivityManager.RunningServiceInfo info : serviceList) {
            if (info.service.getClassName().equals(serviceClass.getName()))
                return true;
        }
        return false;
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(RxBusCode.MAIN_POSITION)})
    public void rxBusMain(String position) {
        setCurrentTab(Integer.parseInt(position), false);
    }

    /**
     * 重写返回键事件
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - firstTime > 2000) {
                firstTime = System.currentTimeMillis();
                ToastUtil.showShort("再按一次退出" + getText(R.string.app_name));
            } else {
                App.getInstance().finishActivity();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
